const {verifyToken} = require('../utils/token');
const {userResponseWrapper} = require('../result');
const {readUserData,} = require('../file');

const dealGetRequest = (pathname, request, response) => {
    console.log("pathname::", pathname);
    const requestMap = {
        '/api/firstScreen': () => {
            const jwt = request.headers['authorization'].replace("Bearer ", "");
            console.log("jwt::", jwt);
            const { usable: isSignIn, data, } = verifyToken(jwt);
            console.log("===>::", isSignIn, data);
            // 根据登录状态返回对应信息
            let result = {};
            if(isSignIn) {
                // 获取用户唯一 key
                const userList = readUserData();
                const user = userList.filter(item => item?.key === data?.userKey)[0];
                if(!user) {
                    // 数据库中无此用户，去注册
                    result = userResponseWrapper(JSON.stringify({
                        loginStatus: false,
                        registered: false,
                    }));
                };
                result = userResponseWrapper(JSON.stringify({
                    loginStatus: true,
                    registered: true,
                    userInfo: {
                        userName: user?.userName,
                        role: user?.role,
                        pages: user?.pages,
                    },
                }));
            }else {
                // token 验证失败去登录
                result = userResponseWrapper(JSON.stringify({
                    loginStatus: false,
                    registered: true,
                }));
            }
            response.setHeader('Content-Type', 'application/json');
            response.write(result);
            response.end();
        },
    };
    requestMap[pathname]();
};

module.exports = dealGetRequest;